package com.jin.webvideo.js.loadClass;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HTMLElement {
    private Element currentElement;
    HTMLElement(Element parent){
        this.currentElement = parent;
    }
    public HTMLElement getElementById(String id){
        return convert(currentElement.getElementById(id));
    }
    public HTMLElement[] getElementsByTagName(String tag){
        return convert(currentElement.getElementsByTag(tag));
    }
    public HTMLElement[] getElementsByClassName(String className){
        return convert(currentElement.getElementsByClass(className));
    }
    public HTMLElement[] getElementsByTagNameNS(String nameSpace, String className) throws Exception {
        throw new Exception("unsupported method getElementsByTagNameNS");
    }
    public HTMLElement[] getElementsByName(String name){
        return convert(currentElement.getElementsByAttributeValue("name", name));
    }
    public HTMLElement[] querySelectorAll(String cssQuery){
        return convert(currentElement.select(cssQuery));
    }
    public HTMLElement querySelector(String cssQuery){
        return convert(currentElement.selectFirst(cssQuery));
    }
    public String getAttribute(String attr){
        return currentElement.attr(attr);
    }
    public void setAttribute(String attr, String value){
        currentElement.attr(attr, value);
    }
    public String html(){
        return currentElement.html();
    }
    public void html(String html){
        currentElement.html(html);
    }
    public String text(){
        return currentElement.text();
    }
    public void text(String text){
        currentElement.text();
    }

    private static HTMLElement[] convert(Elements elements){
        if (elements == null){
            return new HTMLElement[0];
        }
        int len = elements.size();
        HTMLElement[] htmlElements = new HTMLElement[len];
        for (int i = 0; i < len; i++){
            htmlElements[i] = convert(elements.get(i));
        }
        return htmlElements;
    }

    private static HTMLElement convert(Element element){
        return new HTMLElement(element);
    }
}
